<!doctype html>
<html lang="en">
	<head>
		<title>Face tracker</title>
		<meta charset="utf-8">
         
		 <link type="text/css" rel="stylesheet" href="stylesheets/materialize.min.css"  media="screen,projection"/> 
		  
		<style>
			/*@import url(https://fonts.useso.com/css?family=Lato:300italic,700italic,300,700);*/
			
			body {
				/*font-family: 'Lato';*/
				background-color:#ff5252;
				margin: 0px auto;
				
			}
			
			#overlay {
				position: absolute;
				top: 0px;
				left: 0px;
				-o-transform : scaleX(-1);
				-webkit-transform : scaleX(-1);
				transform : scaleX(-1);
				-ms-filter : fliph; /*IE*/
				filter : fliph; /*IE*/
				width : 600px;
				height : 450px;
			}

			#videoel {
				-o-transform : scaleX(-1);
				-webkit-transform : scaleX(-1);
				transform : scaleX(-1);
				-ms-filter : fliph; /*IE*/
				filter : fliph; /*IE*/
                -o-border-radius:30px;
                -webkit-border-radius:30px;
                border-radius:30px;
				width : 600px;
				height : 450px;
			}
			
			#container {
				position : relative;
				width : 600px;
				/*margin : 0px auto;*/
			}
			
			#content {				
				margin-left : auto;
				margin-right : auto;
				max-width: 600px;
			}
			
			#sketch, #filter {
				display: none;
			}
			
			
			.btn {
				/*font-family: 'Lato';*/
				font-size: 16px;
                position: relative;
			}

			#controls {
                
				text-align: center;
			}

			#emotion_container {
				width: 600px;
			}

			#emotion_icons {
				height: 50px;
				padding-left: 30px;
			}

			.emotion_icon {
				width : 40px;
				height : 40px;
				margin-top: 5px;
				/*margin-left : 13px;*/
				/*margin-left : 35px;*/
			}
			#icon1{
				margin-left:3px; 
			}
            #icon2{
            	margin-left:73px;
            }
            #icon3{
            	margin-left:73px;
            	
            }

			#emotion_chart, #emotion_icons {
				margin: 0 auto;
				width : 400px;
			}

			#icon1, #icon2, #icon3 {
				visibility :hidden;
			}

			/* d3 */
			.bar {
				fill : steelblue;
				fill-opacity : .9;
			}

		</style>
	</head>
	<body >
		<script src="javascripts/utils.js"></script>
		<script src="javascripts/emonitor.min.js"></script>
		<script src="javascripts/model_pca_20_svm_emotionDetection.js"></script>
		<script src="javascripts/Stats.js"></script>
		<script src="javascripts/d3.min.js"></script>
		<script src="javascripts/emotion_classifier.js"></script>
		<script src="javascripts/emotionmodel.js"></script>
		<script type="text/javascript" src="javascripts/smoothie.js"></script>
		<script src="/socket.io/socket.io.js"></script>
		<script type="text/javascript" src="javascripts/jquery.min.js"></script>
        <nav>
            <div class="nav-wrapper">
              <a href="#" class="brand-logo center">情绪监测</a>
              <ul id="nav-mobile" class=" hide-on-med-and-down">
                <li class="left"><a class="modal-trigger" href="#modal1"><i class="mdi-action-account-child"></i></a></li>
                <li class="right"><a class="modal-trigger" href="#modal2"><i class="mdi-action-assignment"></i></a></li>  
              </ul>
            </div>
        </nav>

		<div id="content">
			<div id="container">
				<video id="videoel" width="400" height="300" preload="auto" loop class=" z-depth-1" >				
                </video>
				<canvas id="overlay" width="400" height="300"></canvas>
                <canvas id="sketch" width="400" height="300"></canvas>
    			<div id="controls">
                    <a id="startbutton" class="waves-effect waves-light btn" onclick="startVideo()">Start</a>
                </div>
            </div>	
			
			
			
    <div class="row" >
    <div class="col s12">
      <ul class="tabs" >
        <li class="tab col s4"><a href="#test1">柱形图</a></li>
        <li class="tab col s4"><a class="active" href="#test2">曲线图</a></li>
        <li class="tab col s4"><a href="#test3">表情语</a></li>
      </ul>
    </div>
    <div id="test1" class="col s12">
         <div id="emotion_container">
				<div id="emotion_icons">
					<img class="emotion_icon" id="icon1" src="media/icon_sad.png">
					<img class="emotion_icon" id="icon2" src="media/icon_happy.png">
					<img class="emotion_icon" id="icon3" src="media/icon_surprised.png">
				</div>
				<div id='emotion_chart'></div>
			</div>
    </div>
    <div id="test2" class="col s12">
      <canvas id="emonitor" width="578" height="100"></canvas>
    </div>
    <div id="test3" class="col s12">Test 3</div>
    
  </div>

  <!-- Modal Structure -->
  <div id="modal1" class="modal">
    <div class="modal-content">
      <div class="col s12 m8 offset-m2 l6 offset-l3">
        <div class="card-panel grey lighten-5 z-depth-1">
          <div class="row valign-wrapper">
            <div class="col s4">
              <img src="images/1.jpg" alt="" class="circle responsive-img"> <!-- notice the "circle" class -->
            </div>
            <div class="col s10">
              <span class="black-text">
                姓名：熊找平<br>
                职务：哈哈哈
              </span>
            </div>
          </div>

          <div class="row valign-wrapper">
            <div class="col s4">
              <img src="images/1.jpg" alt="" class="circle responsive-img"> <!-- notice the "circle" class -->
            </div>
            <div class="col s10">
              <span class="black-text">
                姓名：熊招平<br>
                职务：哈哈哈
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-footer">
      <a href="#!" class=" modal-action modal-close waves-effect waves-green btn-flat">close</a>
    </div>
  </div>



<!-- Modal Structure -->
 

  <!-- Modal Structure -->
  <div id="modal2" class="modal modal-fixed-footer">
    <div class="modal-content">
      <h4>作品介绍</h4>
      <p>A bunch of textlkdjfl;ajdfandlkjfalk</p><br>
      <p>A bunch of textlkdjfl;ajdfaner dlkjfalk</p><br>
      <p>A bunch of textlkdjfl;ajdfedfdergtrtlkjfalk</p><br>
      <p>A bunxtlkdjfl;ajandlkjfalk</p><br>
      <p>A bunch of textlkdjfl;ajdfandlkjfafergr ttlk</p><br>
    </div>
    <div class="modal-footer">
      <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">Close</a>
    </div>
  </div>
          


			<script>
				var vid = document.getElementById('videoel');
				var overlay = document.getElementById('overlay');
				var overlayCC = overlay.getContext('2d');
				
				/********** check and set up video/webcam **********/

				function enablestart() {
					var startbutton = document.getElementById('startbutton');
					startbutton.value = "start";
					startbutton.disabled = null;
				}
				
				
				navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
				window.URL = window.URL || window.webkitURL || window.msURL || window.mozURL;

				// check for camerasupport
				if (navigator.getUserMedia) {
					// set up stream
					
					var videoSelector = {video : true};
					if (window.navigator.appVersion.match(/Chrome\/(.*?) /)) {
						var chromeVersion = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
						if (chromeVersion < 20) {
							videoSelector = "video";
						}
					};
				
					navigator.getUserMedia(videoSelector, function( stream ) {
						if (vid.mozCaptureStream) {
							vid.mozSrcObject = stream;
						} else {
							vid.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
						}
						vid.play();
					}, function() {
						//insertAltVideo(vid);
						alert("There was some problem trying to fetch video from your webcam. If you have a webcam, please make sure to accept when the browser asks for access to your webcam.");
					});
				} else {
					//insertAltVideo(vid);
					alert("This demo depends on getUserMedia, which your browser does not seem to support. :(");
				}

				vid.addEventListener('canplay', enablestart, false);
				
				/*********** setup of emotion detection *************/

				var ctrack = new clm.tracker({useWebGL : true});
				ctrack.init(pModel);

				function startVideo() {
					// start video
					vid.play();
                    startbutton.style.display="none";
					// start tracking
					ctrack.start(vid);
					// start loop to draw face
					drawLoop();
					//monitor 
					var strokecolor= ["rgb(0, 255, 0)","rgb(255, 0, 0)","rgb(0, 0, 255)"];
					var line0 = new TimeSeries();
					var line1 = new TimeSeries();
					var line2 = new TimeSeries();
					//emit extreme
					var socket = io.connect(); 					
					setInterval(function() {
						line0.append(new Date().getTime(), lineplot0);
						line1.append(new Date().getTime(), lineplot1);
						line2.append(new Date().getTime(), lineplot2);
var data = {};
    data.timeline = new Date().getTime();  
    data.unhappy = lineplot0; 
    data.happy = lineplot1; 
    data.surprise = lineplot2;

var epost = $.ajax( {    
    url:'/emotion',// 跳转到 action    
    data:JSON.stringify(data),
    type:'post',    
    cache:false,    
    contentType: 'application/json',  
    // success: function(data) {
    //     console.log('success');
    //                     },
    //  error : function() {    
    //       // view("异常！");    
    //       alert("异常！");    
    //  }    
});  
						if (lineplot2 > 0.4) {
						socket.emit('surprise',{to:'all',from:'Eric',msg:'Wow!!!!!!'});
						}
						if (lineplot0 > 0.4) {
						socket.emit('surprise',{to:'all',from:'Eric',msg:'我操!'});
						}
						if (lineplot1 > 0.9) {
						socket.emit('surprise',{to:'all',from:'Eric',msg:'哈哈!'});
						}

					}, 500);
					var smoothie = new SmoothieChart({ grid: { strokeStyle: 'rgb(125, 0, 0)', fillStyle: 'rgb(60, 0, 0)', lineWidth: 1, millisPerLine: 250, verticalSections: 6 } });
					smoothie.addTimeSeries(line0, { strokeStyle: strokecolor[0], lineWidth: 2 });
					smoothie.streamTo(document.getElementById("emonitor"), 1000);
					smoothie.addTimeSeries(line1, { strokeStyle: strokecolor[1], lineWidth: 2 });
					smoothie.streamTo(document.getElementById("emonitor"), 1000);
					smoothie.addTimeSeries(line2, { strokeStyle: strokecolor[2], lineWidth: 2 });
					smoothie.streamTo(document.getElementById("emonitor"), 1000);
				}
				
				function drawLoop() {
					requestAnimFrame(drawLoop);
					overlayCC.clearRect(0, 0, 400, 300);
					// var escore = "score :" + ctrack.getScore().toFixed(4);
					if (ctrack.getCurrentPosition()) {
						ctrack.draw(overlay);
					}
					var cp = ctrack.getCurrentParameters();	
					var er = ec.meanPredict(cp);
					
					if (er) {
						lineplot0 = er[0].value;
						lineplot1 = er[1].value;
						lineplot2 = er[2].value;
						updateData(er);

						for (var i = 0;i < er.length;i++) {
							if (er[i].value > 0.4) {
								document.getElementById('icon'+(i+1)).style.visibility = 'visible';
							} else {
								document.getElementById('icon'+(i+1)).style.visibility = 'hidden';
							}

						}

					}
				}
				
                /*** emonitor ***/
				// function emonitor(){

				// }

				var ec = new emotionClassifier();
				ec.init(emotionModel);
				var emotionData = ec.getBlank();	
				
				/************ d3 code for barchart *****************/

				var margin = {top : 20, right : 20, bottom : 10, left : 40},
					width = 400 - margin.left - margin.right,
					height = 100 - margin.top - margin.bottom;

				var barWidth = 30;

				var formatPercent = d3.format(".0%");
				
				var x = d3.scale.linear()
					.domain([0, ec.getEmotions().length]).range([margin.left, width+margin.left]);

				var y = d3.scale.linear()
					.domain([0,1]).range([0, height]);

				var svg = d3.select("#emotion_chart").append("svg")
					.attr("width", width + margin.left + margin.right)
					.attr("height", height + margin.top + margin.bottom)
				
				svg.selectAll("rect").
				  data(emotionData).
				  enter().
				  append("svg:rect").
				  attr("x", function(datum, index) { return x(index); }).
				  attr("y", function(datum) { return height - y(datum.value); }).
				  attr("height", function(datum) { return y(datum.value); }).
				  attr("width", barWidth).
				  attr("fill", "#2d578b");

				svg.selectAll("text.labels").
				  data(emotionData).
				  enter().
				  append("svg:text").
				  attr("x", function(datum, index) { return x(index) + barWidth; }).
				  attr("y", function(datum) { return height - y(datum.value); }).
				  attr("dx", -barWidth/2).
				  attr("dy", "1.2em").
				  attr("text-anchor", "middle").
				  text(function(datum) { return datum.value;}).
				  attr("fill", "white").
				  attr("class", "labels");
				
				svg.selectAll("text.yAxis").
				  data(emotionData).
				  enter().append("svg:text").
				  attr("x", function(datum, index) { return x(index) + barWidth; }).
				  attr("y", height).
				  attr("dx", -barWidth/2).
				  attr("text-anchor", "middle").
				  attr("style", "font-size: 16").
				  attr("fill", "white").
				  text(function(datum) { return datum.emotion;}).
				  attr("transform", "translate(0, 18)").
				  attr("class", "yAxis");

				function updateData(data) {
					// update
					var rects = svg.selectAll("rect")
						.data(data)
						.attr("y", function(datum) { return height - y(datum.value); })
						.attr("height", function(datum) { return y(datum.value); });
					var texts = svg.selectAll("text.labels")
						.data(data)
						.attr("y", function(datum) { return height - y(datum.value); })
						.text(function(datum) { return datum.value.toFixed(1);});

					// enter 
					rects.enter().append("svg:rect");
					texts.enter().append("svg:text");

					// exit
					rects.exit().remove();
					texts.exit().remove();
				}

				/******** stats ********/

				stats = new Stats();
				stats.domElement.style.position = 'absolute';
				stats.domElement.style.top = '0px';
				document.getElementById('container').appendChild( stats.domElement );

				// update stats on every iteration
				document.addEventListener('clmtrackrIteration', function(event) {
					stats.update();
				}, false);

                // function hidestart() {
                //     startbutton.style.display="none";
                // }

			</script>
		</div>
	

	</body>
		<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="javascripts/materialize.min.js"></script>
<script>
 $(document).ready(function(){
    $('ul.tabs').tabs();
  });
</script>
<script>
 $(document).ready(function(){
    // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
    $('.modal-trigger').leanModal();
  });
</script>
</html>
